package com.gdk.ksoft.ui.works;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.gdk.ksoft.R;
import com.gdk.ksoft.assembly.dbhelper.FfindGoodsDbHelper;
import com.gdk.ksoft.data.entry.tables.GoodsTable;
import com.gdk.ksoft.assembly.dbhelper.FworkDbHelper;
import com.gdk.ksoft.ui.works.adapters.PfindGoodsAdapter;
import com.gdk.ksoft.assembly.dialog.NSingleProductDialog;
import com.gdk.ksoft.assembly.utils.system.SQLiteUtils;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.lidroid.xutils.view.annotation.event.OnItemClick;

import java.util.ArrayList;
import java.util.List;

/**
 * 查找商品页面
 */
public class FindGoodsActivity extends Activity{

    public static final int REQ_CODE_GOODS_BRAND = 0x0001;//请求商品品牌的码
    public static final int REQ_CODE_GOODS_GROUP = 0x0002;//请求商品分组的码

    @ViewInject(R.id.pfindGoods_etGoodsSearch)private EditText etGoodsSearch;//搜索框
    @ViewInject(R.id.pfindGoods_lstGoods)private ListView lstGoods;//商品列表

    private static final int PAGE_COUNT = 20;//每页最大加载20条数据
    private int currentPageIndex  = 0,pageCount = 0;//当前页码数和页码总数
    private List<GoodsTable> tmpGoodslist = new ArrayList<GoodsTable>();//临时商品数据源
    private List<GoodsTable> goodslist = new ArrayList<GoodsTable>();//商品数据源
    private PfindGoodsAdapter goodsAdapter;//商品列表数据适配器
    private int netCustomerId = 0;//客户网络ID
    private int netAddressId =0;//收货地址网络ID
    private String customerPriceName;//客户价格名称
    private DbUtils dbUtils;//数据库操作对象

    public static final int MSG_UPDATE_LISTVIEW = 0x0001;//更新商品列表的通知
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch(msg.what){
                case MSG_UPDATE_LISTVIEW://更新列表的通知
                    List<GoodsTable> tmplist = (ArrayList<GoodsTable>)msg.obj;
                    if(tmplist == null || tmplist.size()<=0) return;
                    tmpGoodslist.clear();
                    tmpGoodslist.addAll(tmplist);//获得所有数据
                    goodslist.clear();//清空原数据列表
                    goodsAdapter.notifyDataSetChanged();
                    int dataLen = tmpGoodslist.size();//数据总数
                    currentPageIndex = 0;
                    pageCount = dataLen%PAGE_COUNT == 0?dataLen/PAGE_COUNT:dataLen/PAGE_COUNT+1;
                    if(pageCount == 1){//如果只有1页数据
                        goodslist.addAll(tmpGoodslist.subList(0, dataLen % PAGE_COUNT == 0?PAGE_COUNT:dataLen%PAGE_COUNT));
                    }else{
                        goodslist.addAll(tmpGoodslist.subList(0,PAGE_COUNT));
                    }
                    goodsAdapter.notifyDataSetChanged();
                    lstGoods.setSelection(0);
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_find_goods);
        ViewUtils.inject(this);
        dbUtils = SQLiteUtils.getInstance(this).getDbUtils();
        Intent intent = getIntent();
        if(intent!=null){
            netCustomerId = intent.getIntExtra("netCustomerId",0);//获取客户网络ID
            netAddressId = intent.getIntExtra("netAddressId",0);//获取收货地址网络ID
            customerPriceName = intent.getStringExtra("priceName");//获取客户价格名称
        }
        initActivity();//初始化页面操作
    }

    /**
     * 初始化页面
     */
    public void initActivity(){
        goodsAdapter = new PfindGoodsAdapter(this,goodslist);
        lstGoods.setAdapter(goodsAdapter);
        lstGoods.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                int lastPos = view.getLastVisiblePosition();
                if(scrollState == SCROLL_STATE_IDLE && lastPos == view.getCount()-1){
                    currentPageIndex ++;
                    if(currentPageIndex > pageCount -1){//如果已经超出最后一页了
                        currentPageIndex = pageCount - 1;
                        return;
                    }
                    int dataLen = tmpGoodslist.size();
                    int backPageIndex = currentPageIndex + 1;
                    if(currentPageIndex == pageCount - 1){
                        goodslist.addAll(tmpGoodslist.subList(currentPageIndex*PAGE_COUNT,
                                (dataLen%PAGE_COUNT==0?(backPageIndex*PAGE_COUNT)
                                        :(dataLen%PAGE_COUNT+currentPageIndex*PAGE_COUNT))));
                    }else{
                        goodslist.addAll(tmpGoodslist.subList(currentPageIndex*PAGE_COUNT,backPageIndex*PAGE_COUNT));
                    }
                    goodsAdapter.notifyDataSetChanged();
                }
            }
            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            }
        });
    }

    /**
     * 页面跳转
     * @param cls
     */
    public void gotoNewPage(Class<?> cls,int requestCode){
        Intent intent = new Intent(this,cls);
        intent.putExtra("netCustomerId", netCustomerId);
        intent.putExtra("netAddressId", netAddressId);
        intent.putExtra("priceName", customerPriceName);
        startActivityForResult(intent, requestCode);
        overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
    }

    /**
     * 商品项点击事件,显示新增商品窗口
     * @param av
     * @param view
     * @param position
     * @param itemId
     */
    @OnItemClick(value={R.id.pfindGoods_lstGoods})
    public void onItemClick(AdapterView<?> av,final View view, final int position,long itemId){
        final GoodsTable item = (GoodsTable)lstGoods.getItemAtPosition(position);//获取列表项数据
        Bundle bundle = new Bundle();
        bundle.putInt("netGoodsId", item.id);//传递商品网络ID
        bundle.putString("goodsName", item.mc);//传递商品名称
        bundle.putString("goodsCode",item.tm);//传递商品条码
        bundle.putString("goodsGg",item.gg+item.dw);//传递商品规格
        bundle.putInt("goodsPieceNum",item.mjsl);//商品每件数量
        bundle.putInt("goodsMinMoudleNum",item.mjsl);//传递商品每大件的小件数量
        bundle.putString("goodsMinModule",item.dw);//传递商品的最小计量单位
        bundle.putString("goodsPic", item.slt);//传递商品的图片;
        bundle.putInt("netCustomerId", netCustomerId);//传递客户网络ID
        bundle.putString("priceName", customerPriceName);//传递客户价格名称
        bundle.putInt("netAddressId", netAddressId);//传递收货地址网络ID
        new NSingleProductDialog(this,bundle,new NSingleProductDialog.OnGoodsAddedListener() {
            @Override
            public void onGoodsAdded(int js, int ss,String type) {
//                final PfindGoodsAdapter adapter = (PfindGoodsAdapter)lstGoods.getAdapter();
//                HashMap<String,Object> hashItem = new HashMap<String, Object>();
//                hashItem.put("js",js);//写入件数
//                hashItem.put("ss",ss);//写入散数
//                hashItem.put("type",type);//写入类型
//                adapter.getAlgorithm().set(position,hashItem);
//                adapter.notifyDataSetChanged();
            }
        }).show();//显示添加商品显示框
    }

    @OnClick(value={R.id.pfindGoods_txtSearch,R.id.pfindGoods_txtClear,
            R.id.pfindGoods_txtSearchByBrand,R.id.pfindGoods_txtGroup,
            R.id.pfindGoods_txtGoodsTypes
    })
    public void onViewClick(View view){
        switch(view.getId()){
            case R.id.pfindGoods_txtSearch://搜索操作
                final String keyword = etGoodsSearch.getText().toString();
                if(TextUtils.isEmpty(keyword)){
                    Toast.makeText(this,"搜索的关键字不能为空!",Toast.LENGTH_SHORT).show();
                    return;
                }
                findGoodsByKeyword(this,dbUtils,keyword);//通过关键字查询商品
                break;
            case R.id.pfindGoods_txtClear://清空文字
                etGoodsSearch.setText("");
                break;
            case R.id.pfindGoods_txtSearchByBrand://按品牌查找商品
                gotoNewPage(FindbyBrandActivity.class,REQ_CODE_GOODS_BRAND);
                break;
            case R.id.pfindGoods_txtGroup://按分组
                gotoNewPage(FindbyGroupActivity.class,REQ_CODE_GOODS_GROUP);
                break;
            case R.id.pfindGoods_txtGoodsTypes://同品多味选项
                Intent intent = new Intent(this,FindbyTpdwActivity.class);
                intent.putExtra("customerId",netCustomerId);
                intent.putExtra("addressId",netAddressId);
                startActivity(intent);
                overridePendingTransition(R.anim.slide_in_right,R.anim.slide_out_left);
                break;
        }
    }


    /**
     * 清空所有列表数据
     */
    public void clearAllListData(){
        pageCount = 0;
        currentPageIndex = 0;
        tmpGoodslist.clear();
        goodslist.clear();
        goodsAdapter.notifyDataSetChanged();
    }

    /**
     * 通过关键字查询商品
     * @param keyword
     */
    public void findGoodsByKeyword(final Context context,final DbUtils dbUtils,final String keyword){
        new AsyncTask<Void,Void,Void>(){
            private List<GoodsTable> goodsTableList = null;
            private String errorMessage = null;
            private ProgressDialog  dialog = null;

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                dialog = ProgressDialog.show(context,"","正在加载...");
            }

            @Override
            protected Void doInBackground(Void... params) {
                //查询商品列表
                try {
                    goodsTableList = FworkDbHelper.findGoods(dbUtils, keyword);
                }catch(Exception e){
                    e.printStackTrace();
                    errorMessage = e.getMessage();
                }
                return null;
            }
            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                if(errorMessage==null) {
                    if(dialog != null && dialog.isShowing()) dialog.dismiss();
                    if(goodsTableList == null || goodsTableList.size() <= 0){
                        clearAllListData();//清空列表数据
                        Toast.makeText(context,"未能查找到相关的商品!",Toast.LENGTH_SHORT).show();
                        return;
                    }
                    handler.obtainMessage(MSG_UPDATE_LISTVIEW,goodsTableList).sendToTarget();
                }else {
                    clearAllListData();//清空列表数据
                    Toast.makeText(context, "查询商品出错!", Toast.LENGTH_SHORT).show();
                }
            }
        }.execute();
    }

    /**
     * 根据品牌ID查询所有商品
     * @param context
     * @param brandId
     */
    public void findAllGoodsByBrandId(final Context context,final DbUtils dbUtils,final int brandId){
        new AsyncTask<Void,Void,Void>(){
            private List<GoodsTable> goodsTableList = null;
            private String errorMessage = null;
            private ProgressDialog  dialog = null;

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                dialog = ProgressDialog.show(context,"","正在加载...");
            }
            @Override
            protected Void doInBackground(Void... params) {
                try{
                    goodsTableList = FfindGoodsDbHelper.findAllGoodsByBrandId(dbUtils, brandId);
                }catch (Exception e){
                    errorMessage = e.getMessage();
                    e.printStackTrace();
                }
                return null;
            }
            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                if(dialog != null && dialog.isShowing()) dialog.dismiss();
                if(errorMessage!=null){
                    clearAllListData();//清空列表数据
                    Toast.makeText(context,"查找商品出错!",Toast.LENGTH_SHORT).show();
                    return;
                }
                if(goodsTableList == null || goodsTableList.size()<=0){
                    clearAllListData();//清空列表数据
                    Toast.makeText(context,"没有该品牌的商品!",Toast.LENGTH_SHORT).show();
                    return;
                }
                handler.obtainMessage(MSG_UPDATE_LISTVIEW,goodsTableList).sendToTarget();
            }
        }.execute();
    }

    /**
     * 根据分组ID查询所有商品
     * @param context
     * @param groupId
     */
    public void findAllGoodsByGroupId(final Context context,final DbUtils dbUtils,final int groupId){
        new AsyncTask<Void,Void,Void>(){
            private List<GoodsTable> goodsTableList = null;
            private String errorMessage = null;
            private ProgressDialog  dialog = null;

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                dialog = ProgressDialog.show(context,"","正在加载...");
            }
            @Override
            protected Void doInBackground(Void... params) {
                try{
                    goodsTableList = FfindGoodsDbHelper.findAllGoodsByGroupId(dbUtils, groupId);
                }catch (Exception e){
                    errorMessage = e.getMessage();
                    e.printStackTrace();
                }
                return null;
            }
            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                if(dialog != null && dialog.isShowing()) dialog.dismiss();
                if(errorMessage!=null){
                    clearAllListData();//清空列表数据
                    Toast.makeText(context,"查找商品出错!",Toast.LENGTH_SHORT).show();
                    return;
                }
                if(goodsTableList == null || goodsTableList.size()<=0){
                    clearAllListData();//清空列表数据
                    Toast.makeText(context,"没有该分组的商品!",Toast.LENGTH_SHORT).show();
                    return;
                }
                handler.obtainMessage(MSG_UPDATE_LISTVIEW,goodsTableList).sendToTarget();
            }
        }.execute();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch(requestCode){
            case REQ_CODE_GOODS_BRAND://品牌
                if(resultCode == Activity.RESULT_OK && data!=null)//根据品牌ID查询所有商品
                    findAllGoodsByBrandId(this,dbUtils,data.getIntExtra("brandId",0));
                break;
            case REQ_CODE_GOODS_GROUP://分组
                if(resultCode == Activity.RESULT_OK && data!=null)//根据品牌ID查询所有商品
                    findAllGoodsByGroupId(this,dbUtils,data.getIntExtra("groupId",0));
                break;
            default:
                break;
        }
    }

    /**
     * 页面返回
     */
    public void goBack() {
        setResult(RESULT_OK);
        this.finish();
        overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
    }

    @OnClick(value = {R.id.pfindGoods_imgBack})
    public void OnBackClick(View view) {
        goBack();//页面返回
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK) {
            goBack();//页面返回
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }



}
